package com.hrms.hrms_security.controller;


import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.google.code.kaptcha.Producer;
import com.hrms.common.vo.ResultMessage;
import com.hrms.hrms_security.component.PasswordEncoder2;
import com.hrms.hrms_security.entity.SysUsr;
import com.hrms.hrms_security.service.SysUsrService;

import com.hrms.common.utils.RedisUtil;
import com.hrms.hrms_security.vo.AccountUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * (SysUsr)表控制层
 *
 * @author makejava
 * @since 2024-03-28 14:07:42
 */
@RestController
@RequestMapping("/sysUsr")
@Api("系统人员接口")
public class SysUsrController extends ApiController {
    /**
     * captcha 验证码
     */
    @Resource
    private SysUsrService sysUsrService;

    @Resource
    PasswordEncoder2 passwordEncoder2;
    @Resource
    Producer producer;
    @Resource
    RedisUtil redisUtil;
    @Resource
    RedisTemplate redisTemplate;

    @GetMapping("/captcha")
    public ResultMessage Captcha() throws IOException {
        String key = UUID.randomUUID().toString();
        String code = producer.createText();
        BufferedImage image = producer.createImage(code);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", outputStream);

        Base64.Encoder encoder = Base64.getEncoder();
        String str = "data:image/jpeg;base64,";
        String redis_key = "captcha_codes:" + key;
        String base64Img = str + encoder.encodeToString(outputStream.toByteArray());

        // 构建 Data URL
//        String dataUrl = "data:image/jpeg;base64," + base64Img;
        redisUtil.setRedisTemplate(redisTemplate);
        redisUtil.setEx(redis_key, code, 120L, TimeUnit.SECONDS);

        return new ResultMessage<>(ResultMessage.Success,"获取图片验证码成功",
                MapUtil.builder()
                        .put("userKey", redis_key)
                        .put("captcherImg", base64Img)
                        .build()
        );
    }


    /**
     * 分页查询所有数据
     *
     * @param page   分页对象
     * @param sysUsr 查询实体
     * @return 所有数据
     */
    @PreAuthorize("hasAuthority('sys:admin:list')")
    @RequestMapping(value = "/selectAll", method = RequestMethod.GET)
    @ApiOperation("查询全部")
    @ApiOperationSupport(order = 1)
    public ResultMessage selectAll(Page<SysUsr> page, SysUsr sysUsr) {
        Page<SysUsr> page1 = this.sysUsrService.page(page, new QueryWrapper<>(sysUsr));
        return new ResultMessage(ResultMessage.Success, "查询成功", page1);
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id
     * @return 单条数据
     */
    @PreAuthorize("hasAuthority('sys:admin:list')")
    @RequestMapping(value = "/selectById/{id}", method = RequestMethod.GET)
    @ApiOperation("根据id查询")
    @ApiOperationSupport(order = 2)
    public ResultMessage selectOne(@PathVariable("id") Long id) {
        return new ResultMessage(ResultMessage.Success,"查询成功",this.sysUsrService.getById(id));
    }

    /**
     * 登录功能 JWT
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ApiOperation("用户登录")
    @ApiOperationSupport(order = 3)
    public ResultMessage usrLogin(@RequestBody SysUsr sysUsr) {
        ResultMessage resultMessage = this.sysUsrService.usrLogin(sysUsr);
        return resultMessage;
    }

    /**
     * 获取登录信息
     *
     * @param
     * @return
     */
    @GetMapping("/accountUser")
    @ApiOperation("登录信息")
    public ResultMessage accountUser() {
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken)SecurityContextHolder.getContext().getAuthentication();
        AccountUser user = (AccountUser) authentication.getPrincipal();
        user.setAuthorities(authentication.getAuthorities());
        return new ResultMessage(ResultMessage.Success,"",user);
    }

    /**
     * 退出登录功能
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/loginout", method = RequestMethod.POST)
    @ApiOperation("退出登录")
    @ApiOperationSupport(order = 4)
    public ResultMessage loginOut() {
        return this.sysUsrService.loginOut();
    }

    /**
     * 用户注册
     *
     * @param
     * @return
     */
    @PostMapping("/register")
    @ApiOperation("用户注册")
    @ApiOperationSupport(order = 5)
    public ResultMessage usrRegister(@RequestBody SysUsr sysUsr) throws Exception {
        return sysUsrService.usrRegister(sysUsr);

    }


    /**
     * 新增数据
     *
     * @param sysUsr 实体对象
     * @return 新增结果
     */
    @PostMapping
    public R insert(@RequestBody SysUsr sysUsr) {
        return success(this.sysUsrService.save(sysUsr));
    }

    /**
     * 修改数据
     *
     * @param sysUsr 实体对象
     * @return 修改结果
     */
    @PutMapping
    public R update(@RequestBody SysUsr sysUsr) {
        return success(this.sysUsrService.updateById(sysUsr));
    }

    /**
     * 删除数据
     *
     * @param idList 主键结合
     * @return 删除结果
     */
    @DeleteMapping
    public R delete(@RequestParam("idList") List<Long> idList) {
        return success(this.sysUsrService.removeByIds(idList));
    }
}

